package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.format
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.toJsonString
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.time.LocalDateTime
import java.util.*

@Component
class YjClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://op.yunjiglobal.com/opgateway/api/openapi"

    fun execute(store: Store, method: String, request: Map<String, Any>): JsonObject {
        val authorization = store.authorization
        val signMap = TreeMap<String, String>()
        signMap["method"] = method
        signMap["timestamp"] = LocalDateTime.now().format()
        signMap["format"] = "json"
        signMap["app_key"] = authorization["app_key"]
        signMap["v"] = "3.0"
        signMap["sign_method"] = "md5"
        signMap["session"] = authorization["session"]
        val builder = StringBuilder()
            .append(authorization["app_secret"])
            .append(signMap.entries.joinToString("") { it.key + it.value })
            .append(request.toJsonString())
            .append(authorization["app_secret"])
        val sign = DigestUtils.md5Hex(builder.toString()).uppercase()

        val urlBuilder = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .queryParam("sign", sign)
        signMap.forEach { urlBuilder.queryParam(it.key, it.value) }
        val url = urlBuilder.build(false).toUri()
        val headers = HttpHeaders()
        headers.contentType = MediaType.APPLICATION_JSON
        val requestEntity = HttpEntity<Any>(request, headers)
        return restTemplate.exchange(url, HttpMethod.POST, requestEntity, String::class.java).body!!.toJsonObject()
    }
}